<?php
namespace common\models;



class BalanceLog extends BaseModel
{

    protected  static $logType=[
        1=>'USDT余额',
        2=>'UPH余额',
        3=>'合约钱包',
        4=>'收益钱包',
    ];
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'balance_log';
    }


    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['mch_id', 'member_id', 'balance_id', 'balance_type', 'source_type', 'log_type', 'source_id', 'create_time','is_lock','is_await'], 'integer'],
            [['balance', 'old_balance'], 'number'],
            [['note'], 'string'],
            [['bonus_from'], 'string', 'max' => 64],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'mch_id' => '商户id',
            'member_id' => 'Member ID',
            'balance' => '增加或减少的钱',
            'balance_id' => '账本标识',
            'balance_type' => '账本类型',
            'source_type' => '//来源类型',
            'log_type' => '日志类型（增加1、减少0）',
            'source_id' => '如果来源为订单，即为订单id,如果来源为分红，则为分红日志id',
            'old_balance' => '上次金额',
            'note' => '备注',
            'bonus_from' => '分红的来源',
            'create_time' => '时间',
            'is_lock'      =>'是否是冻结余额',
            'is_await'     =>'是否是待签约金额'
        ];
    }    

	/*
		* 数据列表
		* whereArr 条件
		* params 基本参数 包含 field order page limit
		* extends  扩展信息 一些相关的信息
		* 
	*/	
	public static function dataList($whereArr, $params, $extends = array())
	{
        $model  = self::find();
        $where  = isset($whereArr['where'])?$whereArr['where']:[];
        $whereAnd = isset($whereArr['whereAnd'])?$whereArr['whereAnd']:[];
        $wheres=[];
        if (isset($params['type']) && $params['type']==6) {
            /*获取当前用户锁定余额*/
            $suoding = BalanceLog::getAll(['member_id' => $where['member_id'], 'is_lock' => 1], 'id');
            $id = array_column($suoding, 'id');
            $where['id'] = $id;
            $source_ids = [];
            $source_id = [];
            /*判断当前用户中奖的时间点*/
            $winning = GroupWinning::getAll(['member_id' => $where['member_id'], 'is_order' => 2], 'winning_time,group_detail_id');
            foreach ($winning as $k => $v) {
                if (time() < strtotime($v['winning_time'])) {
                    $source_ids[] = $v['group_detail_id'];
                } else {
                    $source_id[] = $v['group_detail_id'];
                }
            }
            if ($params['select'] == 1 && $source_ids) {
                $wheres = 'member_id=' . $where['member_id'] . ' and source_id in(' . implode(',', $source_ids) . ')';

            } elseif ($params['select'] == 2) {
                unset($where['id']);
                $where['source_id'] = $source_id;
            }
        }
        if (isset($where['member_name']) && $where['member_name']){
            $id_arr = Member::getAll(['like','member_name',$where['member_name']],'member_id,member_name');
            if ($id_arr){
                $idArr = array_column($id_arr,'member_id');

                unset($where['member_name']);
                array_push($idArr,$where['member_id']??'');
                $where['member_id']=$idArr;

            }
        }
        $models = self::queryFormarts($model,$where,$params,$whereAnd,$wheres);
        $model  = $models['model'];
        self::$pages = $models['pages'];

        $data  = $model->asarray()->all();
        if(!$data) return array();

        //操作类型 //账本类型名
        $typeText = \Yii::$app->params['sourceTypeText'];

        foreach($data as &$val)
        {
            $val['type_text'] = isset($typeText[$val['source_type']]) ? $typeText[$val['source_type']] : '类型未设置';

            $val['balance_type']  = self::$logType[$val['balance_type']];
            $val['create_time'] = date('Y-m-d H:i:s',$val['create_time']);
            foreach($extends as $eType)
            {
                if($eType=='member')
                {
                    $field = ['member_name','member_avatar','member_mobile'];
                    $member = Member::getMemberById($val['member_id'],$field);
                    if($member) $val = array_merge($member,$val);
                }
            }
        }
        return $data;
	}

	public static function getOne($where, $field = ['*'])
	{
		return self::find()->select($field)->where($where)->asarray()->one();
	}


	public static function getAll($where = [], $field = ['*'])
	{
		return self::find()->select($field)->where($where)->asarray()->all();
	}


    /*
        组装查询 针对是数据的分页查询
        $model  对象
        $where  条件
        $params  参数
    */
    public static function queryFormarts($model, $where, $params, $whereAnd = array(),$wheres)
    {
        $field = ['*'];

        if(isset($params['field'])) $field = $params['field'];

        //分页
        if(isset($params['page']) && $params['page']>0){
            $page   = $params['page'];
            $limit  = $params['limit']?$params['limit']:10;
            $offset = ($page-1)*$limit;
        }else{
            $offset = '';
            $limit  = '';
        }
        $model = $model->select($field)->where($where);
        if ($wheres){
            $model =  $model->orWhere($wheres);
        }
        if($whereAnd){
            foreach($whereAnd as $and){
                $model = $model->andFilterWhere($and);
            }
        }

        if(isset($params['group'])){
            $model = $model->groupBy($params['group']);
        }

        if(isset($params['order'])){
            $models = $model->orderBy($params['order']);
        }

        self::$query = $model;

        //总数量
        $totalNums = $model->count();
        $models = $model->offset($offset)->limit($limit);
//       var_dump($model->createCommand()->getRawsql());exit();
        self::$pages = $totalNums;
        return array(
            'model'	=> $models,
            'pages'	=> $totalNums?$totalNums:0,
        );
    }

}